#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
美尔雅（sh.600107）日 K 线极值统计
"""

import pandas as pd
from pathlib import Path
from datetime import datetime

# 测试模式只显示1支股票：'sh.600107'
debug_mode = False
stock_code = 'sh.600107'

def analysis_stock(stock_code, data_path= 'daily_data'):
    # 1. 读数据 ----------------------------------------------------------
    file_path = Path(data_path, f'{stock_code}.csv')
    #print('process:', file_path)
    if not file_path.exists():
        #raise FileNotFoundError('请把 sh600107.csv 放在当前目录下！')
        return None

    dtype_spec = {
        "code": "string",
        "open": pd.Float32Dtype(),    # 可空 float
        "high": pd.Float32Dtype(),
        "low": pd.Float32Dtype(),
        "close": pd.Float32Dtype(),
        "preclose": pd.Float32Dtype(),
        "volume": pd.Int64Dtype(),    # 可空 int
        "amount": pd.Float64Dtype(),
        "adjustflag": pd.Int8Dtype(),
        "turn": pd.Float32Dtype(),
        "tradestatus": pd.Int8Dtype(),
        "pctChg": pd.Float32Dtype(),
        "isST": pd.Int8Dtype()
    }
    
    df = pd.read_csv(file_path, dtype=dtype_spec, parse_dates=["date"])   # date列解析成datetime64[ns]
    
    # 转换日期格式
    df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d %H:%M:%S', errors='coerce')

    # 选择2025/07/01及以后的非ST数据
    df = df[(df['date'] >= '2025-01-01') & (df['isST'] != 2)]

    if len(df) == 0:
        return None

    # 2. 定位极值记录 ----------------------------------------------------
    max_rec = df.loc[df['high'].idxmax()]
    if len(max_rec) == 0:
        return None
    
    min_rec = df.loc[df['date'] > max_rec.date]
    if len(min_rec) == 0:
        return None
    min_rec = min_rec.loc[min_rec['low'].idxmin()]
    if len(min_rec) == 0:
        return None
    

    # 3. 提取所需指标 ----------------------------------------------------
    isSt = max_rec['isST']
    max_price = max_rec['high']
    min_price = min_rec['low']
    max_date  = max_rec['date']
    min_date  = min_rec['date']
    
    delta_days1 = (min_date - max_date).days          # 相差天数（可正可负）
    delta_days2 = (datetime.now() - min_date).days    # 相差天数（可正可负）
    ratio = min_price / max_price                     # 最低/最高 占比
    ratio = float(f'{ratio:.4f}')
    
    # 4. 汇总结果 ---------------------------------------------------------
    return [1,                                      # 0 值为1表示符合条件, 其他值无效
            stock_code,                             # 1 股票代码
            str(isSt),                              # 2 是否ST股
            f'{max_date.strftime("%Y-%m-%d")}',     # 3 最大值日期
            f'{min_date.strftime("%Y-%m-%d")}',     # 4 最小值日期
            delta_days1,                            # 5 相差天数（可正可负）
            str(max_price),                         # 6 最高价
            str(min_price),                         # 7 最低价
            f'{1-ratio:.4f}',                       # 8 最低/最高 占比
            delta_days2                             # 9 最低距今天数
            ]
    

if debug_mode:
    res = analysis_stock('sh.600107')
    print(res)
    exit()

root = Path('daily_data').resolve()          # 支持相对/绝对路径
if not root.exists():
    raise FileNotFoundError(f'{root} 目录不存在')

print('符合,代码,ST股,最大值日期,最小值日期,下跌天数,最高价,最低价,降幅比,最低距今天数')
for csv_file in root.rglob('*.csv'):         # 递归扫描
    name_without_suffix = csv_file.stem
    abs_path = csv_file.resolve()
    try:
        # ['sh.603612', '2025-09-08', '2025-09-23', 15, 29.38, 25.04, '85.23%', 5]
        res = analysis_stock(name_without_suffix)[1:]
        if res is None:
            # print(f'0, {stock_code}')
            continue
        print(str(res)[1:-1].replace("'", ""))
    except Exception as e:
        print(f'0, {stock_code}, {str(e)}')

print('All done.')